package com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.file;

/**
 * @author Nail
 */
public final class FileUploader {

    private UploadHandler uploadHandler;

    public final void addUploadHandler(UploadHandler uploadHandler) {
        this.uploadHandler = uploadHandler;
    }

    public final void onUploadProgress(Float percentage) {
        if (this.uploadHandler != null) this.uploadHandler.onUploadProgress(percentage);
    }

    public final void onUploadCompleted(String savedFileName) {
        if (this.uploadHandler != null) this.uploadHandler.onUploadCompleted(savedFileName);
    }

    public final void onUploadError() {
        if (this.uploadHandler != null) this.uploadHandler.onUploadError();
    }

    public final native void upload(File file, String url) /*-{
        var _this = this;
        var reader = new FileReader();
        reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
        reader.onloadend  = function(evt)
        {
            // create XHR instance
            xhr = new XMLHttpRequest();

            // send the file through POST
            xhr.open("POST", url, true);

            // make sure we have the sendAsBinary method on all browsers
            XMLHttpRequest.prototype.mySendAsBinary = function(text){
                var data = new ArrayBuffer(text.length);
                var ui8a = new Uint8Array(data, 0);
                for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);

                if(typeof window.Blob == "function")
                {
                    var blob = new Blob([data]);
                }else{
                    var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
                    bb.append(data);
                    var blob = bb.getBlob();
                }

                this.send(blob);
            }

            // let's track upload progress
            var eventSource = xhr.upload || xhr;
            eventSource.addEventListener("progress", function(e) {
                // get percentage of how much of the current file has been sent
                var position = e.position || e.loaded;
                var total = e.totalSize || e.total;
                var percentage = Math.round((position/total)*100);
                // here you should write your own code how you wish to proces this
                _this.@com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.file.FileUploader::onUploadProgress(Ljava/lang/Float;)(percentage);
            });

            // state change observer - we need to know when and if the file was successfully uploaded
            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4)
                {
                    if(xhr.status == 200)
                    {
                        // process success
                        var savedFileName = xhr.responseText;
                        _this.@com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.file.FileUploader::onUploadCompleted(Ljava/lang/String;)(savedFileName);
                    }else{
                        // process error
                        _this.@com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.file.FileUploader::onUploadError()();
                    }
                }
            };

            // start sending
            xhr.mySendAsBinary(evt.target.result);
        };
    }-*/;
}
